import webpack, { Configuration } from "webpack";

import { resolve, join } from "path";
import WebpackBar from "webpackbar";
import FriendlyErrorsWebpackPlugin from "friendly-errors-webpack-plugin";
import { CleanWebpackPlugin } from "clean-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import { PROJECT_ROOT } from "../env";

const ruleRegex = {
  tsx: /\.tsx?$/,
  less: /\.less$/,
  css: /\.css$/,
};

const loaders = (importLoaders: number) => {
  return [
    "style-loader",
    {
      loader: "css-loader",
      options: {
        importLoaders,
        modules: {
          localIdentName: "[name]__[hash:base64:8]",
        },
      },
    },
  ];
};

const commonConfig: Configuration = {
  context: PROJECT_ROOT,
  // 定义入口文件
  entry: {
    app: [resolve(PROJECT_ROOT, "src/index")],
  },
  //定义生成文件
  output: {
    publicPath: "/",
    path: resolve(PROJECT_ROOT, "dist"),
    chunkFilename: "[name].[chunkhash].js",
    hashSalt: "management",
  },
  // 定义默认导入的文件后缀
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"],
  },
  module: {
    rules: [
      {
        test: ruleRegex.tsx,
        use: "babel-loader",
        exclude: /node-module/,
      },
      {
        test: ruleRegex.css,
        use: loaders(0),
      },
      {
        test: ruleRegex.less,
        use: [...loaders(1), "less-loader"],
      },
    ],
  },
  plugins: [
    new FriendlyErrorsWebpackPlugin(),
    new WebpackBar({
      color: "#61dafb",
      name: "Client",
    }),
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: join(__dirname, "../../public/index.html"),
    }),
    new webpack.DefinePlugin({
      PUBLIC_URL: resolve(__dirname, "../../public"),
    }),
  ],
};

export default commonConfig;
